package com.ltkj.baseplatform.controller;

import com.ltkj.baseplatform.domain.WuserExt;
import com.ltkj.baseplatform.service.IWXUserService;
import com.ltkj.common.core.constant.CacheConstants;
import com.ltkj.common.core.constant.TokenConstants;
import com.ltkj.common.core.domain.R;
import com.ltkj.common.core.utils.JwtUtils;
import com.ltkj.common.core.utils.StringUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.log.annotation.Log;
import com.ltkj.common.log.enums.BusinessType;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.system.api.domain.SysUser;
import com.ltkj.system.api.domain.WxUser;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/wxUser")
@Api(tags = "微信用户相关")
public class WXUserController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private IWXUserService wxUserService;

    @Log(title = "微信用户登录", businessType = BusinessType.INSERT)
    @ApiOperation("微信用户登录")
    @GetMapping("/wxLogin")
    public R<?> wxLogin(String code){
        return wxUserService.wxLogin(code);
    }

    @Log(title = "修改微信用户信息", businessType = BusinessType.UPDATE)
    @ApiOperation("修改微信用户信息")
    @PostMapping("/edit")
    public R<?> editUser(@RequestBody WuserExt user){
        return wxUserService.editUser(user);
    }

    @Log(title = "微信用户退出", businessType = BusinessType.INSERT)
    @ApiOperation("微信用户退出")
    @GetMapping("/wxLogout")
    public R<?> wxLogout(HttpServletRequest request){
        //令牌为空、令牌已过期或验证不正确、登录状态已过期都提示退出成功
        String token = getToken(request);
        //令牌为空
        if (StringUtils.isEmpty(token)) {
            return R.ok();
        }
        //令牌已过期或验证不正确
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null)
        {
            return R.ok();
        }
        String userkey = JwtUtils.getUserKey(claims);
        boolean islogin = redisService.hasKey(getTokenKey(userkey));
        //登录状态已过期
        if (!islogin)
        {
            return R.ok();
        }
        return wxUserService.wxLogout();
    }

    @ApiOperation("获取微信用户信息")
    @GetMapping("/info")
    public R<WxUser> getWxUserInfo(@RequestParam Long userId){
        return wxUserService.getWxUserInfo(userId);
    }

    @ApiOperation("获取微信用户信息V2")
    @GetMapping("/infoV2")
    public R<WuserExt> getWxUserInfoV2(@RequestParam Long userId){
        return wxUserService.getWxUserInfoV2(userId);
    }

    /**
     * 获取请求token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 校验身份证号码是否唯一
     */
    @ApiOperation(value = "校验身份证号码是否唯一")
    @PostMapping("/checkIdCodeUnique")
    public AjaxResult checkIdCodeUnique(@RequestBody Map<String, String> data)
    {
        if (StringUtils.isEmpty(data.get("idCode"))) {
            return AjaxResult.error("身份证号码必填！");
        }
        WuserExt wuserExt = new WuserExt();
        wuserExt.setUserIdcode(data.get("idCode"));
        wuserExt.setUserId(SecurityUtils.getLoginUser().getUserid());
        boolean b = wxUserService.checkIdCardUnique(wuserExt);
        if (b) {
            return AjaxResult.success();
        }
        return AjaxResult.error("当前身份证号码已存在！");
    }
}
